package com.emm.yixun.mobile.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.MainGridAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetProjectBusinessList;
import com.emm.yixun.mobile.model.GetProjectBusinessList.HomePageList;
import com.emm.yixun.mobile.model.GetProjectList;
import com.emm.yixun.mobile.ui.NextUpDateActivity;
import com.emm.yixun.mobile.ui.NotSignedActivity;
import com.emm.yixun.mobile.ui.RemindActivity;
import com.emm.yixun.mobile.ui.SignRecordActivity;
import com.emm.yixun.mobile.ui.SignReturnMoneyActivity;
import com.emm.yixun.mobile.ui.SubscribeRecordActivity;
import com.emm.yixun.mobile.ui.ToExamineActivity;
import com.emm.yixun.mobile.ui.notice.NoticeFragmentActivity;
import com.emm.yixun.mobile.ui.web.WebActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import xf.tools.Loading;

/**
 * <p>
 * <b>Title：</b> 首页
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 *
 * @author tangxin
 * @date 2016年12月13日 下午6:17:32
 */
public class MainFragment extends Fragment {

    private static final String TAG = "MainFragment";

    /**
     * 项目列表数据源
     */
    GetProjectList GetProject;

    /**
     * 业务列表数目
     */
    GetProjectBusinessList getbusiness;

    FragmentActivity root = null;

    View view;

    /**
     * 弹出框View
     */
    View viewproject;

    /**
     * 弹出框
     */
    PopupWindow popuproject;

    /**
     * 标题
     */
    TextView title_main;

    /**
     * 商家图标
     */
    ImageView left_icon;

    /**
     * 右边箭头
     */
    ImageView right_icon;

    /**
     * 选中的项目
     */
    private int SelectPostion = 0;

    /**
     * 业务列表适配器
     */
    MainGridAdapter maingridAdapter;

    /**
     * 业务列表
     */
    ListView main_listview;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragmenta, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        root = getActivity();
        initView();
        initBtn();
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.v(TAG, "onResume() ID" + JPushInterface.getRegistrationID(root));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            Log.v(TAG, "onHiddenChanged(true) ");
        } else {
            Log.v(TAG, "onHiddenChanged(false) ");
            // 相当于Fragment的onResume
            Reload();
        }
    }

    /**
     * <p>
     * <b>Title：</b> 初始化view
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 上午10:35:35
     */
    private void initView() {
        view = root.findViewById(R.id.main_include);
        main_listview = (ListView) root.findViewById(R.id.main_listview);
        RelativeLayout main_head_top_rela = (RelativeLayout) root.findViewById(R.id.main_include).findViewById(
                R.id.main_head_top_rela);
        BaseActivity.SetViewHeight(main_head_top_rela);// 更改relativelayout的高度
    }

    /**
     * <p>
     * <b>Title：</b> 初始化监听事件方法
     * </p>
     * <p>
     * <b>Description：</b> 菜单列表item点击事件监听并处理
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 上午10:11:19
     */
    private void initBtn() {
        // 监听首页业务列表点击事件，分发处理
        main_listview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if ("公告通知".equals(getbusiness.getHomePageList().get(position).getHomePageName())
                        || "公告".equals(getbusiness.getHomePageList().get(position).getHomePageName())) {
                    startActivity(new Intent(root, NoticeFragmentActivity.class));
                } else if ("逾期未签约".equals(getbusiness.getHomePageList().get(position).getHomePageName())) {
                    WebActivity.Companion.jump(root, "backstage_sign", "逾期未签约");
                } else if ("逾期未付款".equals(getbusiness.getHomePageList().get(position).getHomePageName())) {
                    WebActivity.Companion.jump(root, "backstage_receipt", "逾期未付款");
                } else if ("待处理客户".equals(getbusiness.getHomePageList().get(position).getHomePageName())) {
                    Intent intent = new Intent(root, NotSignedActivity.class);
                    intent.putExtra("NAME", "待处理客户");
                    intent.putExtra("TYPED", "3");
                    startActivity(intent);
                } else if ("审核列表".equals(getbusiness.getHomePageList().get(position).getHomePageName())
                        || "审核申请".equals(getbusiness.getHomePageList().get(position).getHomePageName())) {
                    Intent intent = new Intent(root, ToExamineActivity.class);
                    startActivity(intent);
                } else if ("提醒".equals(getbusiness.getHomePageList().get(position).getHomePageName())) {
                    Intent intent = new Intent(root, RemindActivity.class);
                    startActivity(intent);
                } else if ("下次跟进提醒".equals(getbusiness.getHomePageList().get(position).getHomePageName())) {
                    Intent intent = new Intent(root, NextUpDateActivity.class);
                    startActivity(intent);
                } else if ("未完善信息客户".equals(getbusiness.getHomePageList().get(position).getHomePageName())) {
                    Intent intent = new Intent(root, NotSignedActivity.class);
                    intent.putExtra("NAME", "未完善信息客户");
                    intent.putExtra("TYPED", "4");
                    startActivity(intent);
                } else if ("签约回款提醒".equals(getbusiness.getHomePageList().get(position).getHomePageName())) {
                    startActivity(new Intent(root, SignReturnMoneyActivity.class));
                } else if ("签约".equals(getbusiness.getHomePageList().get(position).getHomePageName())) {
                    startActivity(new Intent(root, SignRecordActivity.class));
                } else if ("认购".equals(getbusiness.getHomePageList().get(position).getHomePageName())) {
                    startActivity(new Intent(root, SubscribeRecordActivity.class));
                }
            }
        });
    }

    /**
     * 耗时打印缓存
     */
    long l1;

    /**
     * <p>
     * <b>Title：</b> 刷新方法
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 上午10:35:56
     */
    public void Reload() {
        l1 = System.currentTimeMillis();
        Log.v(TAG, "起始：" + l1);
        getProjectBusinessList(EmmApplication.getProjectCode());
    }

    /**
     * <p>
     * <b>Title：</b> 首页业务列表数量接口
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param projectCode
     * @author tangxin
     * @date 2016年12月7日 上午10:36:10
     */
    private void getProjectBusinessList(String projectCode) {
        if (!EmmApplication.isErrorCode()) {
            EmmApplication.T();
            return;
        }
        Log.v(TAG, "projectCode:" + projectCode);
        EmmApplication.updateUrl("getProjectBusinessList");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("projectCode", projectCode);
        map.put("projectId", EmmApplication.getProjectID());
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v(TAG, "getProjectBusinessList-->post:" + EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.hideDialogForLoading();
                Loading.showDialogForLoading(root, "正在加载...", false, true, 60000);
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                long l2 = System.currentTimeMillis();
                Log.v(TAG, "结束：" + l2 + "    --- 用时:" + (l2 - l1) + "毫秒");
                long l3 = System.currentTimeMillis();
                Log.v(TAG, "开始本地处理：" + l3);
                Log.v(TAG, "main-->content:" + content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = null;
                try {
                    resData = (JSONObject) jsonObj.get("resData");
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    return;
                }
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }
                getbusiness = JSONObject.parseObject(resData.toString(), GetProjectBusinessList.class);

                if ("1".equals(getbusiness.getResult())) {
                    Log.v("获取成功", "GetProjectBusinessList");
                    if (null != getbusiness.getHomePageList()) {
                        if (maingridAdapter != null) {
                            maingridAdapter.SetDate(getbusiness.getHomePageList());
                        } else {
                            maingridAdapter = new MainGridAdapter(root, getbusiness.getHomePageList());
                            main_listview.setAdapter(maingridAdapter);
                        }
                    } else {
                        ArrayList<HomePageList> list = new ArrayList<>();
                        if (maingridAdapter != null) {
                            maingridAdapter.SetDate(list);
                        } else {
                            maingridAdapter = new MainGridAdapter(root, list);
                            main_listview.setAdapter(maingridAdapter);
                        }
                        EmmApplication.Ts("无业务列表数据");
                    }
                } else {
                    ArrayList<HomePageList> list = new ArrayList<HomePageList>();
                    if (maingridAdapter != null) {
                        maingridAdapter.SetDate(list);
                    } else {
                        maingridAdapter = new MainGridAdapter(root, list);
                        main_listview.setAdapter(maingridAdapter);
                    }
                    EmmApplication.T(getbusiness.getErrorMsg().toString());
                    Log.v("获取失败", "errorCode:" + getbusiness.getErrorCode().toString() + "errorMsg:"
                            + getbusiness.getErrorMsg().toString());
                }
                long l4 = System.currentTimeMillis();
                Log.v(TAG, "结束本地处理：" + l4 + "  -------用时：" + (l4 - l3) + "毫秒");
            }
        });
    }
}
